//
//  FRNearViewController.m
//  Live
//
//  Created by 徐芙蓉 on 2017/7/26.
//  Copyright © 2017年 Afra. All rights reserved.
//

#import "FRNearViewController.h"
#import "FRLiveHandler.h"
#import "FRNearLiveCell.h"
#import "FRPlayerViewController.h"

#define kItemSizeW 100
#define kMargin 5
static NSString * identifier = @"FRNearLiveCell";

@interface FRNearViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *datalist;


@end

@implementation FRNearViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    [self loadData];
    
 
}

-(void)initUI
{
    [self.collectionView registerNib:[UINib nibWithNibName:@"FRNearLiveCell" bundle:nil] forCellWithReuseIdentifier:identifier];
}

-(void)loadData
{
    [FRLiveHandler executeGetNearLiveTaskWithSuccess:^(id obj) {
        NSLog(@"obj = %@",obj);
        self.datalist = obj;
        [self.collectionView reloadData];
    } failed:^(id obj) {
        NSLog(@"%@",obj);
    }];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datalist.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FRNearLiveCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.live = self.datalist[indexPath.row];
    
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    NSInteger count = self.collectionView.width / kItemSizeW;
    
    CGFloat etraWidth = (self.collectionView.width - kMargin * (count + 1)) / count;
    
    return CGSizeMake(etraWidth, etraWidth + 20);
}

//cell将要显示时调用
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    FRNearLiveCell *c = (FRNearLiveCell *)cell;
    
    [c showAnimation];
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    FRLive *live = self.datalist[indexPath.row];
    FRPlayerViewController *playerVC = [[FRPlayerViewController alloc] init];
    playerVC.live = live;
    [self.navigationController pushViewController:playerVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
